package com.friend.chat.net

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.asRequestBody
import java.io.File

/**
 * @des
 * @date 2021/9/24
 * @author gorilla
 */
class ServerRepository {

    //登录
    suspend fun loginByPass(username: String, password: String) = withContext(Dispatchers.IO) {
        val map = HashMap<String, Any>(2)
        map["username"] = username
        map["password"] = password
        RetrofitCreator.server.loginByPassword(map)
    }

    //注册
    suspend fun register(username:String,nickname:String,password:String,phone:String,header:String,sex:Int,age:Int)
            = withContext(Dispatchers.IO) {
        val map = HashMap<String, Any>(2)
        map["username"] = username
        map["nickname"] = nickname
        map["password"] = password
        map["phone"] = phone
        map["header"] = header
        map["sex"] = sex
        map["age"] = age
        RetrofitCreator.server.register(map)
    }

    suspend fun getFriendsList(userId: String) = withContext(Dispatchers.IO) {
        RetrofitCreator.server.getFriendsList(userId)
    }

    suspend fun getGroupList(userId: String) = withContext(Dispatchers.IO) {
        RetrofitCreator.server.getMyGroupList(userId)
    }

    suspend fun getRoomList(userId: String) = withContext(Dispatchers.IO) {
        RetrofitCreator.server.getRoomList(userId)
    }

    suspend fun getUnReadChatList(chatId:String,userId:String) = withContext(Dispatchers.IO) {
        RetrofitCreator.server.getUnReadChatList(chatId,userId)
    }


    suspend fun getUnReadGroupChatList(chatId:String,userId:String) = withContext(Dispatchers.IO) {
        RetrofitCreator.server.getUnReadGroupChatList(chatId,userId)
    }


    suspend fun addFriend(userId:String,friendId:String) = withContext(Dispatchers.IO) {
        RetrofitCreator.server.addFriend(userId,friendId)
    }

    suspend fun createGroup( requestBody: RequestBody)= withContext(Dispatchers.IO) {
        RetrofitCreator.server.createGroup(requestBody)
    }

    //上传图片
    suspend fun uploadHeader(path: String) = withContext(Dispatchers.IO) {
        val requestBody: RequestBody =
            File(path).asRequestBody("image/jpg".toMediaTypeOrNull())
        val multiPart = MultipartBody.Part.createFormData("imageFile", File(path).name, requestBody)
        RetrofitCreator.server.uploadHeader( multiPart)
    }
}